package com.qingcloud.adminbackend.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.qingcloud.adminbackend.constant.WamingConstant;
import com.qingcloud.adminbackend.entity.config.SysDictionaryConfig;
import com.qingcloud.adminbackend.entity.eventlog.EquipmentEventLog;
import com.qingcloud.adminbackend.entity.eventlog.EquipmentEventLogParams;
import com.qingcloud.adminbackend.mapper.SysDictionaryConfigMapper;
import com.qingcloud.adminbackend.service.IEventLogService;
import com.qingcloud.adminbackend.utils.OKHttpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 设备指令服务
 */
@Service
public class EventLogServiceImpl implements IEventLogService {

    private static final Logger logger = LoggerFactory.getLogger(EventLogServiceImpl.class);

    @Resource
    private SysDictionaryConfigMapper sysDictionaryConfigMapper;

    @Value("${healthy.data-url}")
    private String eventLogUrl;

    /**
     * 查询事件列表
     *
     * @param equipmentEventLogParams
     * @return
     */
    @Override
    public Map<String, Object> listEquipmentEventLog(EquipmentEventLogParams equipmentEventLogParams) {
        Map<String, Object> resultMap = new HashMap<>(2);
        // TODO  DcEngine API
        String result = OKHttpUtil.httpPost(eventLogUrl + "edata/equipmentEventLogPage", JSONObject.toJSONString(equipmentEventLogParams));
        Map<String, Object> logResultMap = (Map<String, Object>) JSONObject.parse(result);
        if (null == logResultMap.get("data") || (Integer) logResultMap.get("recordsTotal") == 0) {
            resultMap.put("recordsTotal", 0);
            resultMap.put("data", null);
            return resultMap;
        }
        List<EquipmentEventLog> equipmentEventLogs = JSONObject.parseObject(logResultMap.get("data").toString(), new TypeReference<>() {
        });
        final List<JSONObject> eventLogs = equipmentEventLogs.stream().map(this::parseContent).collect(Collectors.toList());

        resultMap.put("recordsTotal", logResultMap.get("recordsTotal"));
        resultMap.put("data", eventLogs);
        return resultMap;
    }

    @Override
    public List<SysDictionaryConfig> findDeviceTypeByType(Integer type) {

        return sysDictionaryConfigMapper.findByType(type);
    }

    /**
     * 解析content,组合成完整实体类
     *
     * @param equipmentEventLog
     * @return
     */
    private JSONObject parseContent(EquipmentEventLog equipmentEventLog) {
        JSONObject baseEventLogResult = null;
        Integer category = equipmentEventLog.getEventCatagory();
        String content = equipmentEventLog.getContent();
        try {
            if (category == 2) {
                baseEventLogResult = JSONObject.parseObject(content);
                this.toParseEventLog(baseEventLogResult);
            } else if (category == 4) {
                baseEventLogResult = JSONObject.parseObject(content);
                this.toParseResetEventLog(baseEventLogResult);
            } else if (category == 5) {
                baseEventLogResult = JSONObject.parseObject(content);
                this.toParseFaultEventLog(baseEventLogResult);
            } else {
                baseEventLogResult = new JSONObject();
            }
        } catch (Exception e) {
            logger.error("解析失败", e);
        }
        if (baseEventLogResult == null) {
            baseEventLogResult = new JSONObject();
        }
        baseEventLogResult.put("equipmentId", equipmentEventLog.getEquipmentId());
        baseEventLogResult.put("rtcTime", equipmentEventLog.getRtcTime());
        return baseEventLogResult;
    }


    //EventEventLogResult
    private void toParseEventLog(JSONObject eventLog) {

        Integer warningType = eventLog.getInteger("warningType");
        Integer warningText = eventLog.getInteger("warningText");
        Integer warningContent = eventLog.getInteger("warningContent");

        final SysDictionaryConfig configByObjectType = sysDictionaryConfigMapper.findConfigByObject(WamingConstant.EVENT_LOG_EVENT, null, String.valueOf(warningType));
        if (configByObjectType != null) {
            eventLog.put("warningTypeDescription", configByObjectType.getName());
        }
        if (warningType != null) {
            Integer textType = null;
            if (0x04 == warningType) {
                textType = 91;
            } else if (0x0A == warningType) {
                textType = 47;
            } else if (0x0B == warningType) {
                textType = 50;
            } else if (0x0C == warningType) {
                textType = 53;
            } else if (0x0F == warningType) {
                textType = 63;
            } else if (0x10 == warningType) {
                textType = 65;
            }
            if (textType != null) {
                SysDictionaryConfig sysDictionaryConfig = sysDictionaryConfigMapper.findConfigByObject(textType, null, String.valueOf(warningText));
                eventLog.put("warningTextDescription", sysDictionaryConfig.getName());
            }
        }
        if (warningType != null) {
            Integer contentType = null;
            if (0x01 == warningType) {
                contentType = 35;
            } else if (0x02 == warningType) {
                contentType = 36;
            } else if (0x03 == warningType) {
                contentType = 37;
            } else if (0x04 == warningType) {//38的情况
                if (9 == warningText) {//TVOC情况
                    contentType = 38;
                } else {
                    contentType = 39;
                }
            } else if (0x05 == warningType) {
                contentType = 42;
            } else if (0x06 == warningType) {
                contentType = 43;
            } else if (0x07 == warningType) {
                contentType = 44;
            } else if (0x08 == warningType) {
                contentType = 45;
            } else if (0x09 == warningType) {
                contentType = 46;
            } else if (0x0A == warningType) {
                if (0x00 == warningText) {
                    contentType = 48;
                } else if (0x01 == warningText) {
                    contentType = 49;
                }
            } else if (0x0B == warningType) {
                if (0x00 == warningText) {
                    contentType = 51;
                } else if (0x01 == warningText) {
                    contentType = 52;
                }
            } else if (0x0C == warningType) {
                if (0x00 == warningText) {
                    contentType = 54;
                } else if (0x01 == warningText) {
                    contentType = 55;
                }
            } else if (0x0D == warningType) {
                contentType = 61;
            } else if (0x0E == warningType) {
                contentType = 62;
            } else if (0x0F == warningType) {
                contentType = 64;
            } else if (0x10 == warningType) {
                contentType = 66;
            }
            if (contentType != null) {
                SysDictionaryConfig config = sysDictionaryConfigMapper.findConfigByObject(contentType, null, String.valueOf(warningContent));
                eventLog.put("warningContentDescription", config.getName());
            }
        }
    }


    //FaultEventLogResult
    private void toParseFaultEventLog(JSONObject eventLog) {
        int faultCode = eventLog.getIntValue("faultCode");
        final SysDictionaryConfig configByObject = sysDictionaryConfigMapper.findConfigByObject(WamingConstant.EVENT_LOG_FAULT, null, String.valueOf(faultCode));
        if (configByObject != null)
            eventLog.put("faultCodeDescription", configByObject.getName());
    }


    //ResetEventLogResult
    private void toParseResetEventLog(JSONObject eventLog) {
        int resetCause = eventLog.getIntValue("resetCause");
        final SysDictionaryConfig configByObject = sysDictionaryConfigMapper.findConfigByObject(WamingConstant.EVENT_LOG_RESET, null, String.valueOf(resetCause));
        if (configByObject != null)
            eventLog.put("resetCauseDescription", configByObject.getName());
    }


}
